﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace yDevice.ExpanderDevice.ZLG_CAN
{
    public class GCAN212Service
    {
        Socket _client;
        public delegate void RecvHandle(uint addr, byte[] data);
        public RecvHandle RecvEvent;
        public bool IsConnected;
        public void SocketConnect(string ip, int port)
        {
            _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            EndPoint addr = new IPEndPoint(IPAddress.Parse(ip), port);
            _client.Connect(addr);
            byte[] data = new byte[1024];
            string msg = string.Empty;
            if (_client.Connected)
            {
                Task.Run(() =>
                {
                    while (true)
                    {
                        IsConnected = _client.Connected;
                        int len = _client.Receive(data);
                        msg = BitConverter.ToString(data, 0, len).Replace("-", " ");
                        if (len > 5)
                        {
                            if (RecvEvent != null)
                            {
                                byte[] idData = new byte[4];
                                byte[] subData = new byte[len - 5];
                                Array.Copy(data, 1, idData, 0, 4);
                                Array.Copy(data, 5, subData, 0, len - 5);
                                uint id = BitConverter.ToUInt32(idData, 0);
                                RecvEvent.Invoke(id, subData);
                            }
                        }
                        Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss:fff")} : {msg}");
                    }
                });
            }
        }

        public void SendData(string msgId, string data)
        {
            byte[] bytes = new byte[64];
            bytes[0] = Convert.ToByte(msgId.Substring(0, 2), 16);
            bytes[1] = Convert.ToByte(msgId.Substring(2, 2), 16);
            string[] strs = data.Split(' ');
            for (int i = 0; i < strs.Length; i++)
            {
                bytes[i + 2] = Convert.ToByte(strs[i], 16);
            }
            if (_client.Connected)
            {
                _client.Send(bytes);
            }
        }
    }
}
